﻿<%@ Page Title="Administrera enkät" Language="C#" MasterPageFile="~/masterpage.master" AutoEventWireup="true" CodeBehind="SurveyFormEditor.aspx.cs" Inherits="UL360Admin.Survey.SurveyFormEditor" culture="auto" meta:resourcekey="PageResource1" uiculture="auto" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="headcontent" runat="server">
    <link href="<%= Page.ResolveUrl("~/Styles/Survey/SurveyStyles.css") %>" rel="Stylesheet" type="text/css" />
    <link href="<%= Page.ResolveUrl("~/Styles/Survey/jquery-ui-1.10.2.custom.css") %>" rel="Stylesheet" type="text/css" /> 

    <script type="text/javascript">

    //Enable sortables
    $(function () {
        $(".sortable").sortable();
        $(".sortable").disableSelection();
    });
    
    //Enable scale accordion
    $(function () {
        $(".scale-accordion-container").accordion({
            collapsible: true,
            active: false,
            icons: false
        });
        $(".scale-accordion-container1").accordion({
            active: 0
        });
    });

    //Enable text accordion
    $(function () {
        $(".text-accordion-container").accordion({
            collapsible: true,
            active: false,
            icons: false
        });
        $(".text-accordion-container1").accordion({
            active: 0
        });
    });

    //Expand all question panels
    $(function () {
        $("#expandAll").click(function () {
            $(".scale-accordion-container")
                .filter(":not(:has(.ui-state-active))")
                .accordion("activate", 0);
            return false;
        });
        $("#expandAll").click(function () {
            $(".text-accordion-container")
                .filter(":not(:has(.ui-state-active))")
                .accordion("activate", 0);
            return false;
        });
    });

    //Collapse all question panels
    $(function () {
        $("#collapseAll").click(function () {
            $(".scale-accordion-container")
                .filter(":has(.ui-state-active)")
                .accordion("activate", -1);
            return false;
        });
        $("#collapseAll").click(function () {
            $(".text-accordion-container")
                .filter(":has(.ui-state-active)")
                .accordion("activate", -1);
            return false;
        });
    });

    //Messages when saving the survey form
    function success(msg) {
        $("#dialog-modal").dialog("close");
        var returnMessage = JSON.parse(msg);
        if (returnMessage.Status == 0) {
            $("#dialog-modal-message").html("Enkäten är sparad.").dialog("open");
            $("#dialog-modal-message").bind("dialogclose", function (event, ui) {
                window.location.reload(true);
            });
        }
        else {
            $("#dialog-modal-message").html("Ett fel uppstod när enkäten skulle sparas.\n" +
                "Var god försök igen eller kontakta support med följande id:\n" +
                returnMessage.ErrorTicket).dialog("open");
        }
    }

    //Dialog window for progressbar
    $(function () {
        $("#dialog-modal").dialog({
            autoOpen: false,
            modal: true,
            height: "auto",
            width: "auto"
        });
    });

    //Dialog window for messages
    $(function () {
        $("#dialog-modal-message").dialog({
            autoOpen: false,
            height: 200,
            width: 250,
            modal: true
        });
    });

    //Document ready functions
    $(document).ready(function () {
        $(".save-button").click(function () {
            formType = document.getElementById("FormType").value;
            var formValues = getValues();
            var formValuesAsJSON = JSON.parse(formValues);
            
            if (formValuesAsJSON.isEmpty == false) {
                if (formValuesAsJSON.ScaleQuestionTexts.length > 0) {
                    $("#dialog-modal").dialog("open");
                    $.ajax({
                        type: "POST",
                        url: '<%= Page.ResolveUrl(UL360SurveyCommon.Constants.REQUEST_HANDLER_URL) %>?SaveForm=true&FormType=' + formType,
                        data: formValues,
                        success: success,
                        dataType: "html"
                    });
                }
                else {
                    $("#dialog-modal-message").html("För att kunna spara enkäten måste det finnas minst en fråga för typen skala. Lägg till en skalfråga och spara på nytt.").dialog("open");
                }
            }
            else {
                $("#dialog-modal-message").html("För att kunna spara enkäten måste alla frågefält vara ifyllda. Kontrollera och fyll i de fält som är tomma.").dialog("open");
            }
            return false;
        });

        //Enable jquery theme for inputs and buttons
        $(".button").button();
        $("button").button();

        //Delete questions
        $(".trashcan").live("click", function () {
            if (confirm('Varning! \nÄr du säker på att du vill ta bort frågan? \nOBS! Detta går ej att ångra.')) {
                $(this).parent().parent().parent().remove();
                    if (document.getElementsByClassName("sortable-item-scale").length == 0) {
                        document.getElementById("ScaleOrderCount").value = 0;
                    }
                    if (document.getElementsByClassName("sortable-item-text").length == 0) {
                        document.getElementById("TextOrderCount").value = 0;
                    }

                    //Hide buttons if no questions are available
                    if ((document.getElementsByClassName("sortable-item-scale").length == 0) && (document.getElementsByClassName("sortable-item-text").length == 0)) {
                        document.getElementById("ButtonPanel").style.display = "none";
                        document.getElementById("Save1").style.display = "none";
                    }
            }
        });

        //Add click event to new question button
        $("#newScaleQuestion").click(function () {
            //Show save and expand and collapse buttons if hidden
            if (document.getElementById("ButtonPanel").style.display == "none") {
                document.getElementById("ButtonPanel").style.display = "inline";
            }
            if (document.getElementById("Save1").style.display == "none") {
                document.getElementById("Save1").style.display = "inline";
            }

            //Get next order
            var order = parseInt(document.getElementById("ScaleOrderCount").value) + 1;
            document.getElementById("ScaleOrderCount").value = order;

            //Generate HTML to add in question box
            var htmlToAdd = '<li class="sortable-item sortable-item-scale" id="ScaleQuestion' + order + '"><div class="scale-accordion-container"><h3>Fråga ' + order + '<img class="trashcan" title="Ta bort denna fråga" alt="Ta bort" src="<%=Page.ResolveUrl("~/Images/1367804307_Black_Trash.png")%>" /></h3><div class="accordion-item">';
            //Get all languages from hidden field
            var languages = document.getElementById("LanguagesList").value.split(";");
            //Add textbox for each language
            for (var i = 0; i < languages.length - 1; i++) {
                htmlToAdd += "<p>";
                //Get language name
                htmlToAdd += languages[i].split("#")[1] + "<br \>";
                //Add textbox
                htmlToAdd += '<input type="text" id="ScaleQuestionText' + order + '#' + languages[i].split("#")[0] + '" />';
                htmlToAdd += "</p>";
            }
            //Add ending tags
            htmlToAdd += '</div></div></li>';

            //Append html to sortables list
            $("#scaleSortable").append(htmlToAdd);

            //Make accordion of newly added question
            $(".scale-accordion-container").accordion({
                collapsible: true,
                icons: false
            });

            //Don't post form
            return false;
        });

        //Add click event to new question button
        $("#newTextQuestion").click(function () {
            //Show save and expand and collapse buttons if hidden
            if (document.getElementById("ButtonPanel").style.display == "none") {
                document.getElementById("ButtonPanel").style.display = "inline";
            }
            if (document.getElementById("Save1").style.display == "none") {
                document.getElementById("Save1").style.display = "inline";
            }
            //Get next order
            var order = parseInt(document.getElementById("TextOrderCount").value) + 1;
            document.getElementById("TextOrderCount").value = order;

            //Generate HTML to add in question box
            var htmlToAdd = '<li class="sortable-item sortable-item-text" id="TextQuestion' + order + '"><div class="text-accordion-container"><h3>Fråga ' + order + '<img class="trashcan" title="Ta bort denna fråga" alt="Ta bort" src="<%=Page.ResolveUrl("~/Images/1367804307_Black_Trash.png")%>" /></h3><div class="accordion-item">';
            //Get all languages from hidden field
            var languages = document.getElementById("LanguagesList").value.split(";");
            //Add textbox for each language
            for (var i = 0; i < languages.length - 1; i++) {
                htmlToAdd += "<p>";
                //Get language name
                htmlToAdd += languages[i].split("#")[1] + "<br \>";
                //Add textbox
                htmlToAdd += '<input type="text" id="TextQuestionText' + order + '#' + languages[i].split("#")[0] + '" />';
                htmlToAdd += "</p>";
            }
            //Add ending tags
            htmlToAdd += '</div></div></li>';

            //Append html to sortables list
            $("#textSortable").append(htmlToAdd);

            //Make accordion of newly added question
            $(".text-accordion-container").accordion({
                collapsible: true,
                icons: false
            });

            //Don't post form
            return false;
        });

    });

    //Get sorting order of sortables
        function getOrderOfSortables(type) {
            if (type == "scale") {
                var inputs = document.getElementById("scaleSortable").getElementsByTagName("li");
                var splitName = "ScaleQuestion";
            }
            else if (type == "text" ) {
                var inputs = document.getElementById("textSortable").getElementsByTagName("li");
                var splitName = "TextQuestion";
            }

            var sortableOrder = new Array();
            for (var i = 0; i < inputs.length; i++) {
                sortableOrder[i] = inputs[i].id.split(splitName)[1];
            }
            return sortableOrder;
    }

    //Get all textbox values and corresponding question and language id:s
    function getValues() {
        //Pattern for textbox id (questions that exist in db)
        var pattScale = new RegExp("ScaleQuestionText[0-9]*#[0-9]*", i);
        var pattText = new RegExp("TextQuestionText[0-9]*#[0-9]*", i);

        //Object to make JSON from
        var jsonReq = new Object();

        //Get all input elements
        var inputs = document.getElementsByTagName("input");

        //Array with questions
        var scaleQuestions = new Array();

        //Question Index
        var n = 0;

        //Indicates if question textbox is empty
        var isEmpty = false;

        //Loop through all input elements and get textboxes with questiontexts 
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].id.match(pattScale) && inputs[i].value.length > 0) {
                //Question object
                var question = new Object();

                question.InputId = inputs[i].id.match(pattScale)[0];
                question.QuestionNumber = question.InputId.split("ScaleQuestionText")[1].split("#")[0];
                question.LanguageId = question.InputId.split("ScaleQuestionText")[1].split("#")[1];
                question.TextValue = inputs[i].value;

                scaleQuestions[n] = question;

                n++;
            }

            else if (inputs[i].id.match(pattScale) && inputs[i].value.length <= 0) {
                isEmpty = true;
                break;
            }
        }

        if (isEmpty == false) {
            //Array with questions
            var textQuestions = new Array();

            //Question Index
            var n = 0;

            //Loop through all input elements and get textboxes with questiontexts 
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].id.match(pattText) && inputs[i].value.length > 0) {
                    //Question object
                    var question = new Object();

                    question.InputId = inputs[i].id.match(pattText)[0];
                    question.QuestionNumber = question.InputId.split("TextQuestionText")[1].split("#")[0];
                    question.LanguageId = question.InputId.split("TextQuestionText")[1].split("#")[1];
                    question.TextValue = inputs[i].value;

                    textQuestions[n] = question;

                    n++;
                }

                else if (inputs[i].id.match(pattText) && inputs[i].value.length <= 0) {
                    isEmpty = true;
                    break;
                }
            }
            jsonReq.OrderOfScaleSortables = getOrderOfSortables("scale");
            jsonReq.ScaleQuestionTexts = scaleQuestions;
            jsonReq.OrderOfTextSortables = getOrderOfSortables("text");
            jsonReq.TextQuestionTexts = textQuestions;
            jsonReq.FormType = document.getElementById("FormType").value;
            jsonReq.isEmpty = false;
        }

        if (isEmpty == false) {
            return JSON.stringify(jsonReq);
        }
        else {
            var returnJSON = new Object();
            returnJSON.isEmpty = true;
            return JSON.stringify(returnJSON);
        }
    }

 
</script>

</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
    <div class="content-container">
    <asp:SiteMapPath ID="SiteMapPath1" runat="server" CssClass="siteMapPath" meta:resourcekey="SiteMapPath1Resource1"></asp:SiteMapPath>

    <asp:HiddenField ID="LanguagesList" runat="server" ClientIDMode="Static" />
    <asp:HiddenField ID="FormType" runat="server" ClientIDMode="Static" />

    <asp:HiddenField ID="ScaleOrderCount" runat="server" ClientIDMode="Static" />
    <asp:HiddenField ID="TextOrderCount" runat="server" ClientIDMode="Static" />

    <h3><asp:Label ID="EditSurveyTitle" runat="server" Text="Redigera enkätformulär för kursutvärdering del 1"></asp:Label></h3>

    <asp:Label ID="WarningLabel" runat="server" CssClass="survey-warning" meta:resourcekey="WarningLabelResource1"></asp:Label>
    <h4><asp:Label ID="InformationLabel" runat="server" meta:resourcekey="InformationLabelResource1"></asp:Label></h4>
    <p class="content-left">
        <asp:Label ID="DateCreated" runat="server" Text=""></asp:Label><br />
        <asp:Label ID="SurveyVersion" runat="server" Text=""></asp:Label><br />
    </p>  
      
        <asp:Panel ClientIDMode="Static" ID="ButtonPanel" runat="server">
            <asp:Button CssClass="button" ClientIDMode="Static" ID="expandAll" runat="server" Text="Visa alla frågor" meta:resourcekey="ExpandAll"/>
            <asp:Button CssClass="button" ClientIDMode="Static" ID="collapseAll" runat="server" Text="Fäll samman alla frågor" meta:resourcekey="CollapseAll"/>
            <asp:Button CssClass="button save-button element-right" ClientIDMode="Static" ID="Save" runat="server" Text="Spara enkäten" meta:resourcekey="SaveSurvey"/>
        </asp:Panel>

    <div class="survey-questions-container">
        
        <h2>
            <asp:Label ID="ScaleQuestionsHeading" runat="server" meta:resourcekey="ScaleQuestionsHeading"></asp:Label>
        </h2>
        
        <p>
            <asp:Label ID="NoScaleQuestionsInForm" runat="server" meta:resourcekey="InformationLabelResource1"></asp:Label>
            <asp:Button CssClass="button" ClientIDMode="Static" ID="newScaleQuestion" runat="server" Text="Lägg till ny fråga för skala" meta:resourcekey="NewScaleQuestionButton"/>
        </p>
        <asp:Repeater ID="ScaleQuestions" runat="server">
            <HeaderTemplate>

                <ul id="scaleSortable" class="sortable-container sortable">
                
            </HeaderTemplate>

            <ItemTemplate>

                <li class="sortable-item sortable-item-scale" id='ScaleQuestion<%# Eval("Order") %>'>
                    <div class="scale-accordion-container scale-accordion-container<%# Eval("Order") %>">
                        <h3>
                            <asp:Label ID="ScaleQuestionHeading" runat="server" meta:resourcekey="QuestionHeading"></asp:Label> 
                            <asp:Label ID="ScaleQuestionNumber" runat="server" Text='<%# Eval("Order") %>' meta:resourcekey="IDResource1" ></asp:Label>
                            <img class="trashcan" title="Ta bort denna fråga" alt="Ta bort" src="<%= Page.ResolveUrl("~/Images/1367804307_Black_Trash.png") %>" />
                        </h3>

                        <div class="accordion-item">
                            <asp:HiddenField ID="ScaleQuestionId" runat="server" Value='<%# Eval("SurveyQuestionId") %>' />
                            <asp:Repeater ID="Languages" runat="server">
                                <ItemTemplate>
                                    <asp:HiddenField ID="LanguageId" runat="server" Value='<%# Eval("sprakid") %>' />
                                    <p>
                                        <asp:Label ID="LanguageName" runat="server" Text='<%# Eval("namn") %>'></asp:Label><br />
                                        <asp:TextBox ID="ScaleQuestionText" runat="server"></asp:TextBox>
                                    </p>
                                </ItemTemplate>
                            </asp:Repeater>
                        </div>
                    </div>
                </li>
            </ItemTemplate>

            <FooterTemplate>
                </ul>
            </FooterTemplate>
        </asp:Repeater>

        <!-- Fritext -->
        <h2>
            <asp:Label ID="TextQuestionsHeading" runat="server" meta:resourcekey="TextQuestionsHeading"></asp:Label>
        </h2>
        <p>
            <asp:Label ID="NoTextQuestionsInForm" runat="server" meta:resourcekey="InformationLabelResource1"></asp:Label>
            <asp:Button CssClass="button" ClientIDMode="Static" ID="newTextQuestion" runat="server" Text="Lägg till ny fritextfråga" meta:resourcekey="NewTextQuestionButton"/>
        </p>
        <asp:Repeater ID="TextQuestions" runat="server">
            <HeaderTemplate>

                <ul id="textSortable" class="sortable-container sortable">
                
            </HeaderTemplate>

            <ItemTemplate>

                <li class="sortable-item sortable-item-text" id='TextQuestion<%# Eval("Order") %>'>
                    <div class="text-accordion-container text-accordion-container<%# Eval("Order") %>">
                        <h3>
                            <asp:Label ID="TextQuestionHeading" runat="server" meta:resourcekey="QuestionHeading"></asp:Label> 
                            <asp:Label ID="TextQuestionNumber" runat="server" Text='<%# Eval("Order") %>' meta:resourcekey="IDResource1" ></asp:Label>
                            <img class="trashcan" title="Ta bort denna fråga" alt="Ta bort" src="<%= Page.ResolveUrl("~/Images/1367804307_Black_Trash.png") %>" />
                        </h3>

                        <div class="accordion-item">
                            <asp:HiddenField ID="TextQuestionId" runat="server" Value='<%# Eval("SurveyQuestionId") %>' />
                            <asp:Repeater ID="Languages" runat="server">
                                <ItemTemplate>
                                    <asp:HiddenField ID="LanguageId" runat="server" Value='<%# Eval("sprakid") %>' />
                                    <p>
                                        <asp:Label ID="LanguageName" runat="server" Text='<%# Eval("namn") %>'></asp:Label><br />
                                        <asp:TextBox ID="TextQuestionText" runat="server"></asp:TextBox>
                                    </p>
                                </ItemTemplate>
                            </asp:Repeater>
                        </div>
                    </div>
                </li>
            </ItemTemplate>

            <FooterTemplate>
                </ul>
            </FooterTemplate>
        </asp:Repeater>
    </div>
        <div class="content-right"><asp:Button CssClass="button save-button" ClientIDMode="Static" ID="Save1" runat="server" Text="Spara enkäten" meta:resourcekey="SaveSurvey"/></div>
</div>
    <div id="dialog-modal" title="">Sparar...<br /><br /><img alt="Sparar..." src='<%= Page.ResolveClientUrl("~/Images/loader.gif") %>' /></div>
    <div id="dialog-modal-message" title="Meddelande"></div>
</asp:Content>